package com.study.springbootsecurity.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.net.URLEncoder;

import static com.baomidou.mybatisplus.extension.ddl.DdlScriptErrorHandler.PrintlnLogErrorHandler.log;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-06 15:38
 */
@Slf4j
public class ResponseUtil {
    /**
     * 使用response输出JSON
     *
     * @param response
     * @param result
     */
    public static void outJson(ServletResponse response, Object result) {

        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(new ObjectMapper().writeValueAsString(result));
        } catch (Exception e) {
            log.error("{}输出JSON出错", e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            log.error("ResponseUtil的renderString渲染字符串客户端失败检查 字符串格式", e);
        }
        return null;
    }

    /**
     * 使用response输出文件
     *
     * @param response
     * @param is       文件流
     * @param fileName 文件名
     */
    public static void outFile(HttpServletResponse response, InputStream is, String fileName) {
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        // 设置文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        BufferedInputStream bis = null;
        try {
            //中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8");
            OutputStream outputStream = response.getOutputStream();
            //把输入流copy到输出流
            IOUtils.copy(is, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error("ResponseUtil的outFile方法文件输出客户端失败；检查文件", e);
        }
    }
}
